/*
 * @Author: szx
 * @Date: 2022-02-17 13:19:57
 * @LastEditTime: 2022-02-17 13:54:35
 * @Description:
 * @FilePath: \leetcode\2000-2099\2047\2047.js
 */
/**
 * @param {string} sentence
 * @return {number}
 */
// var countValidWords = function (sentence) {
//     sentence.split(' ').filter((w) => console.log(w));
//     return sentence.split(' ').filter((w) => /^([,.!]|[a-z]+(-[a-z]+)?[,.!]?)$/.test(w)).length;
// };

var countValidWords = function (sentence) {
    const arr = sentence.split(' ');
    let res = 0;
    let tmp;
    for (let a of arr) {
        a = a.trim();
        if (a.length != 0) {
            tmp = valid(a);

            console.log(a, tmp);
            res += tmp;
        }
    }
    return res;
};
const valid = (str) => {
    let code = 0;
    for (let i = 0; i < str.length; i++) {
        const s = str[i];
        if (i == 0) {
            // 情况1：字母打头
            if (s >= 'a' && s <= 'z') code = 1;
            // 情况2:标点符号打头
            else if (s == ',' || s == '!' || s == '.') {
                if (i == str.length - 1) return 1;
                else return 0;
            } else return 0;
        } else {
            if (code == 1) {
                if (s >= 'a' && s <= 'z') continue;
                // 情况3，有个连字符‘-’
                else if (s == '-') {
                    if (i == str.length - 1) return 0;
                    else code = 2;;
                }
                // 已经到了文字的末尾
                else if (s == ',' || s == '!' || s == '.') {
                    if (i == str.length - 1) return 1;
                    else return 0;
                } else return 0;
            } else if (code == 2) {
                if (s >= 'a' && s <= 'z') code = 3;
                else return 0;
            } else if (code == 3) {
                if (s >= 'a' && s <= 'z') continue;
                else if ((s == ',' || s == '!' || s == '.') && i == str.length - 1) {
                    return 1;
                } else return 0;
            }
        }
    }
    return 1;
};
console.log(countValidWords('. ! 7hk  al6 l! aon49esj35la k3 7u2tkh  7i9y5  !jyylhppd et v- h!ogsouv 5'));
